package com.ruiyi.adrobot.service.vpn.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruiyi.adrobot.beans.Area;
import com.ruiyi.adrobot.service.vpn.VpnService;
import com.ruiyi.adrobot.utils.RemoteRequestUtil;

import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Created by kennedy on 2017/7/16.
 */
@Service
public class VpnServiceImpl implements VpnService {
    @Resource(name = "redisTemplate")
    private ValueOperations<String, String> redisOperations;
    private static String releaseVpn = "http://router.ipyun.org/api.php/index/release?appid=86841a9147b5e82e699b64886b0325c2&access_token=ACCESS_TOKEN&ip=IP";
    private static String onlineUrl = "http://router.ipyun.org/api.php/index/online?appid=86841a9147b5e82e699b64886b0325c2&access_token=ACCESS_TOKEN";
    private static String switchIpUrl = "http://router.ipyun.org/api.php/index/switchip?appid=86841a9147b5e82e699b64886b0325c2&access_token=ACCESS_TOKEN";

    @Override
    public JSONObject releaseIp(String ip) {
        JSONObject jsonObject = null;
        int sign = 0;
        do {
            jsonObject = RemoteRequestUtil.httpRequest(releaseVpn.replace("ACCESS_TOKEN", redisOperations.get("accessToken")).replace("IP", ip), "GET", null);
            if (sign == 3) {
                break;
            }
            sign++;
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (jsonObject.getInteger("status") == 0);
        return jsonObject;
    }

    @Override
    public JSONObject switchIp(Area area, String param) {
        String accessToken = redisOperations.get("accessToken");
        String requestUrl = switchIpUrl.replace("ACCESS_TOKEN", accessToken);
        switch (area) {
            case ALL:
                break;
            case PROVINCE:
                requestUrl = requestUrl + "&province_id=" + param;
                break;
            case CITY:
                requestUrl = requestUrl + "&city_id=" + param;
                break;
        }
        return RemoteRequestUtil.httpRequest(requestUrl, "GET", null);
    }

    @Override
    public JSONObject getOnlineInfo() {
        return RemoteRequestUtil.httpRequest(onlineUrl.replace("ACCESS_TOKEN", redisOperations.get("accessToken")), "GET", null);
    }
}
